//
//  UIViewController+Tracking.m
//  ZM_MiniSupply
//
//  Created by 谭真 on 15/12/16.
//  Copyright © 2015年 上海千叶网络科技有限公司. All rights reserved.
//  hook每个控制器的出现/消失方法 实现swizz

#import "UIViewController+Tracking.h"
//#import "TalkingData.h"
#import <objc/runtime.h>

@implementation UIViewController (Tracking)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        
        // 1. 实现hock viewWillAppear
        SEL originalSelector = @selector(viewWillAppear:);
        SEL swizzledSelector = @selector(weicang_viewWillAppear:);
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        // 交换这两个方法的实现
        method_exchangeImplementations(originalMethod, swizzledMethod);
        
        // 2. 实现hock viewWillDisappear
        /*
        SEL originSelDisappear = @selector(viewWillDisappear:);
        SEL swizzledSelDisappear = @selector(weicang_viewWillDisappear:);
        Method originalMethodDisappear = class_getInstanceMethod(class, originSelDisappear);
        Method swizzledMethodDisappear = class_getInstanceMethod(class, swizzledSelDisappear);
        method_exchangeImplementations(originalMethodDisappear, swizzledMethodDisappear);
         */
    });
}

#pragma mark - Method Swizzling

- (void)weicang_viewWillAppear:(BOOL)animated {
    /**
     此处调用的weicang_viewWillAppear 即是调用swizz前的viewWillAppear。因为这两个SEL的方法实现已经交换过了。
     
     从而实现了 在每一个控制器的ViewWillAppear方法里，注入相关的代码，比如这里注入了TalkingData的代码，而不用重复地写在每一个控制器的ViewWillAppear里
     */
    [self weicang_viewWillAppear:animated];
    
    // 过滤掉不需要分析数据的控制器
    if ([self isKindOfClass:[UINavigationController class]]) { return;  }
    if ([self isKindOfClass:[UIInputViewController class]])  { return;  }
    if ([self isKindOfClass:[NotepadNavVC class]])       { return;  }
    if ([self isKindOfClass:[NotepadTabBarVC class]])     { return;  }
    
   //
}

- (void)weicang_viewWillDisappear:(BOOL)animated {
    [self weicang_viewWillDisappear:animated];
    
    // 过滤掉不需要分析数据的控制器
    if ([self isKindOfClass:[UINavigationController class]]) { return;  }
    if ([self isKindOfClass:[UIInputViewController class]])  { return;  }
    if ([self isKindOfClass:[NotepadNavVC class]])    { return;  }
    if ([self isKindOfClass:[NotepadTabBarVC class]])    { return;  }
}
@end
